//
//  MDMessageManagerHandler.m
//  MideaWorld_Zizhu
//
//  Created by Minus on 5/21/15.
//  Copyright (c) 2015 Minus. All rights reserved.
//

#import "MDMessageManagerHandler.h"
#import "MDXPGApplianceApi.h"
#import <MideaHomeSDK/MideaHomeSDK.h>

#import <JreEmulation.h>

#define MAX_H2S_LEN 1024

static void h2s(const char *s, long len, char *o)
{
    int c = 0;
    
    memset(o, 0x00, MAX_H2S_LEN);
    
    for(int i = 0; i < len; i++)
    {
        c = s[i];
        sprintf(&o[strlen(o)], "%d,", c);
    }
    
    o[strlen(o)-1] = 0x00;
}

@implementation MDMessageManagerHandler

- (NSString *)encryptStringWithByteArray:(IOSByteArray *)bytes
                            withNSString:(NSString *)applianceId
                            withNSString:(NSString *)accessToken
{
    NSMutableArray *messageArray = [NSMutableArray new];
    
    for (int i = 0; i < [bytes length]; i++)
    {
        [messageArray addObject:@([bytes byteAtIndex:i])];
    }
    
    MideaProtocol *protocol = [[MideaProtocol alloc] init];
    [protocol setMessageMark:[self getMessageID]];
    [protocol setMessageTypeMark:0x0020];   // 0x0020表示数据透传
    [protocol setTerminalID:(int64_t)[applianceId longLongValue]];
    [protocol setMessageArray:messageArray];
    
    NSString *sendString;
    
    long length = [protocol getByteStreamLength];
    char *data = (char *)[protocol getByteStream];
    char cmd[MAX_H2S_LEN] = {0x00};
    h2s(data, length, cmd);
    
    sendString = [MideaDataSecurity sensitiveDataEncryption:accessToken msg:[NSString stringWithUTF8String:cmd]];
    
    return sendString;
}

- (NSString *)decryptStringWithNSString:(NSString *)accessToken
                           withNSString:(NSString *)reply
{
    NSString *decyrptString = [MideaDataSecurity sensitiveDataDecryption:accessToken reply:reply];
    
    return decyrptString;
}

- (int32_t)getMessageID
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMddHHmmss"];
    
    NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
    
    return (int32_t)[dateString intValue];
}

@end
